package appservice

import (
	"context"

	"go-mall/api/reply"
	"go-mall/api/request"
	"go-mall/common/errcode"
	"go-mall/common/logger"
	"go-mall/common/util"
	"go-mall/dal/cache"
	"go-mall/logic/do"
	"go-mall/logic/domainservice"
)

type DemoAppSvc struct {
	ctx           context.Context
	demoDamainSvc *domainservice.DemoDomainSvc
}

func NewDemoAppSvc(ctx context.Context) *DemoAppSvc {
	return &DemoAppSvc{
		ctx:           ctx,
		demoDamainSvc: domainservice.NewDemoDomainSvc(ctx),
	}
}

func (das *DemoAppSvc) GetDemoIdentities() ([]int64, error) {
	demos, err := das.demoDamainSvc.GetDemos()
	if err != nil {
		return nil, err
	}
	identities := make([]int64, 0, len(demos))
	for _, demo := range demos {
		identities = append(identities, demo.Id)
	}
	return identities, nil
}

func (das *DemoAppSvc) CreateDemoOrder(
	demoOrderCreate *request.DemoOrderCreate,
) (*reply.DemoOrder, error) {
	demoOrderDo := new(do.DemoOrder)

	if err := util.CopyProperties(demoOrderDo, demoOrderCreate); err != nil {
		err = errcode.Wrap("demoOrderCreate转换demoOrderDo失败", err)
		return nil, err
	}

	// if demoOrderDo.PaidAt.IsZero() {
	// 	// paidAt为空，则设置为1970-01-01 00:00:01
	// 	demoOrderDo.PaidAt = time.Unix(1, 0)

	// 	// demoOrderDo.PaidAt =
	// }
	// fmt.Println("demoOrderDo", demoOrderDo)

	demoOrderDo, err := das.demoDamainSvc.CreateDemoOrder(demoOrderDo)
	if err != nil {
		return nil, err
	}

	cache.SetDemoOrder(das.ctx, demoOrderDo)
	cacheData, _ := cache.GetDemoOrder(das.ctx, demoOrderDo.OrderNo)
	logger.New(das.ctx).Info("redis data", "data", cacheData)

	replyDemoOrder := new(reply.DemoOrder)
	if err := util.CopyProperties(replyDemoOrder, demoOrderDo); err != nil {
		err = errcode.Wrap("demoOrderDo转换replyDemoDrder失败", err)
		return nil, err
	}
	return replyDemoOrder, err
}
